/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Client;
import java.net.*; 
import java.io.*;
import java.util.Timer;
import java.util.TimerTask;

public class Client {

    public static void main (String [] args ) { 
        //TimerTask timerTask = new RemindTask();
        Timer timer = new Timer();
        System.out.println("Autorun...");
        timer.schedule(new RemindTask(),200, 30*1000);
    }
}

class RemindTask extends TimerTask {
        @Override
        public void run() {
            try (Socket socket = new Socket("112.213.84.190",5217)) {
            System.out.println("Connecting to Server: "+socket);      
            FileService service = new FileService(socket);
            service.displayMenu();
            } catch (Exception ex) {
                System.out.println("Error: "+ex.getMessage());
            }
            // timer.cancel(); //Terminate the timer thread
        }
}

class FileService {
    protected DataOutputStream out;
    protected DataInputStream in;
    private BufferedOutputStream bos=null;
    private BufferedInputStream bis=null;
    Socket s;
    FileService(Socket socket) {
        try {
            this.s=socket;
            out = new DataOutputStream(s.getOutputStream());
            in = new DataInputStream(s.getInputStream());
        } catch (IOException ex) {
            System.out.println("Error: "+ex.getMessage());
        }
    }
    public void displayMenu() throws Exception
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        try
        {    
            int choice;
            System.out.println("[ --MENU-- ]");
            System.out.println("1. Send File");
            System.out.println("2. Receive File");
            System.out.println("3. Exit");
            System.out.print("\nEnter Choice :");            
            choice=Integer.parseInt(br.readLine());
            if(choice==1)
            {
                out.writeUTF("S");
                String filename;
                System.out.print("Enter File Name :");
                filename=br.readLine();
                File transferFile = new File (filename);
                SendFile(transferFile);
            }
            else if(choice==2)
            {
                out.writeUTF("G");
                out.writeUTF("123");
                out.flush();
                int listSize = in.readInt();
                for(int i=0;i<listSize;i++)
                    ReceiveFile();
            }
            else
            {
                out.writeUTF("DISCONNECT");
                System.exit(1);
            }
            
        }catch (Exception ex ){
            System.out.println("Error: "+ex.getMessage());
        }
        finally{
            out.flush();
            if(bis!=null)
                bis.close();
            if(bos!=null)
                bos.close();
            out.close();
            in.close();
            s.close();
            System.out.println("Disconnect from: "+s.getInetAddress()+"");
        }
    }
    public void SendFile(File transferFile) throws IOException
    {
        FileInputStream fis = null;
        try {
            out = new DataOutputStream(s.getOutputStream());
            if(!transferFile.exists())
            {
                      System.out.println("File invalid");
                      out.writeUTF("Fileinvalid");
                      return;
            }
            else out.writeUTF("Filevalid");
            fis = new FileInputStream(transferFile);
            byte [] bytearray  = new byte [1024*10];
            bis = new BufferedInputStream(fis);
            int size= fis.available();
            
            int c=-1;
            System.out.println("Sending...");
            long start = System.currentTimeMillis();
            long skip = 0;
            //bis.skip(50*1024*1024);
            while((c = bis.read(bytearray,0,bytearray.length)) != -1)
            {
                      out.write(bytearray, 0, c);
                      size -= c;
                      System.out.printf("Remaining %.2f Kb %n",(float)size/1024);
                      skip+=c;        
            }
            
            System.out.println("\nFile transfer complete in: "+(System.currentTimeMillis()-start)/1000 + " s.");
        } catch (FileNotFoundException ex) {
        }
        finally{}
    }
    
    public void ReceiveFile()
    {
        try {
            String fileName = "C:\\FileClient\\"+in.readUTF()+"";
            //Receive file
            byte [] bytearray  = new byte [1024*10];
            if(in.readUTF().compareTo("Fileinvalid")==0)
                return;
            
            FileOutputStream fos = new FileOutputStream(fileName);
            bos = new BufferedOutputStream(fos);
            
            int n=-1;
            int completed=0;
            int fileSize = in.readInt();
            System.out.println("Get file: "+fileName+" -- Size: "+(float)fileSize/1000+"Kb");
            long start = System.currentTimeMillis();
            while ((n = in.read(bytearray)) > -1){
                fos.write(bytearray, 0, n);
                completed+=n;
                System.out.printf("Received %.2f Kb\n",(float)completed/1000);
                if(completed>=fileSize) break;
            }
            
            long end = System.currentTimeMillis();
            System.out.println("Receive successfuly "+(float)completed/1000 + "Kb written in " + (end-start)/1000 + " s.");
        } catch (IOException ex) {
            System.out.println("Error: "+ex.getMessage());
        } finally {}
    }
    
    public void CheckFile(File file)
    {
    
    }
}

